//
//  CZUploadPicViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/24.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZUploadPicViewController.h"
#import "CZUploadPicCell.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AssetsLibrary/AssetsLibrary.h>

static NSString * const upload_pic_cell = @"upload_pic_cell";
@interface CZUploadPicViewController () <UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *uploadPicTableView;
@property (nonatomic, strong) NSMutableArray *picArray;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (nonatomic, strong) LGRefreshView *refreshView;
@property (nonatomic, assign) NSInteger currentPage;
@end

@implementation CZUploadPicViewController

- (NSMutableArray *__nonnull)picArray {
    if (!_picArray) {
        _picArray = [[NSMutableArray alloc] init];
    }
    return _picArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上传作品";
    _currentPage = 1;
    _uploadPicTableView.estimatedRowHeight = 75;
    _uploadPicTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_uploadPicTableView registerNib:[UINib nibWithNibName:@"CZUploadPicCell" bundle:nil] forCellReuseIdentifier:upload_pic_cell];
    self.addBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self postPicData];
    
    _refreshView = [LGRefreshView refreshViewWithScrollView:self.uploadPicTableView
                                             refreshHandler:^(LGRefreshView *refreshView){
                                                 _currentPage = 1;
                                                 self.uploadPicTableView.mj_footer.state = MJRefreshStateIdle;
                                                 [self postPicData];
                                             }];
    _refreshView.center = CGPointMake(Main_Screen_Width / 2, _refreshView.center.y);
    _refreshView.tintColor = ThemeColor;
    _refreshView.backgroundColor = [UIColor clearColor];
    
    // 注册
    self.uploadPicTableView.mj_footer = [MJDIYBackFooter footerWithRefreshingBlock:^{
        _currentPage ++;
        [self postPicData];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:CZLoginSuccessNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [self postPicData];
    }];

    
    // Do any additional setup after loading the view from its nib.
}
- (IBAction)addAction:(UIButton *)sender {
    UIAlertController *alertController = [[UIAlertController alloc] init];
    UIAlertAction *photoLibraryAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imageaPicker = [[UIImagePickerController alloc] init];
        UIImagePickerControllerSourceType sourceTypePhoto = UIImagePickerControllerSourceTypePhotoLibrary;
        imageaPicker.sourceType = sourceTypePhoto;
        imageaPicker.delegate = self;
        
        [self presentViewController:imageaPicker animated:YES completion:^{
            
        }];
    }];
    
    //访问受限
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"照相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"摄像头访问受限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertC animated:YES completion:nil];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertC addAction:action];
        } else if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *imageaPicker = [[UIImagePickerController alloc] init];
            UIImagePickerControllerSourceType sourceTypePhoto = UIImagePickerControllerSourceTypeCamera;
            imageaPicker.sourceType = sourceTypePhoto;
            imageaPicker.delegate = self;
            [self presentViewController:imageaPicker animated:YES completion:^{
                
            }];
        }
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:photoLibraryAction];
    [alertController addAction:cameraAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}


#pragma mark - 选择图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    [SVProgressHUD showWithStatus:@"上传中"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage* image = [[UIImage alloc] init];
        image = [self fixOrientation:[info objectForKey:UIImagePickerControllerOriginalImage]];
        NSData *compressData = UIImageJPEGRepresentation(image, 0.75);
        
        CZNsjHelper *helper = [[CZNsjHelper alloc] init];
        @weakify(self);
        [helper uploadObjectSyncWithObjectKey:@"doujin_pic" fileData:compressData successStatus:nil errorStatus:@"上传失败" completion:^(NSString *urlString) {
            [weak_self savePicDataWithIMGURL:urlString image:image];
        }];
    });
    
}

- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (void)savePicDataWithIMGURL:(NSString *)imageURL image:(UIImage *)image {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/doujin/upload-doujin",APP_HOST];
    if (![[NSUserDefaults standardUserDefaults] objectForKey:User_Token]) {
        CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        CZNavigationController *naviVC = rootVC.childViewControllers[0];
        CZMessionCenterViewController *homeVC = (CZMessionCenterViewController *)naviVC.childViewControllers[0];
        CZNavigationController *mineNC = rootVC.childViewControllers[4];
        CZMineViewController *mineVC = mineNC.childViewControllers[0];
        CZUserLoginViewController * loginVC = [[[CZNsjHelper alloc] init] presentLoginViewControllerWithViewCotroller:self];
        @weakify(mineVC);
        loginVC.callBack = ^(){
            [weak_mineVC getUserData];
            [homeVC setUserIconImage];
            weak_mineVC.userIconImageView.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
            [self savePicDataWithIMGURL:imageURL image:image];
        };
        return;
    }
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"doujin_type" : self.uploadTpye, @"pic_width" : @(image.size.width), @"pic_height" : @(image.size.height), @"doujin_pic" : imageURL} success:^(id response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self postPicData];
            });
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.picArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZUploadPicCell *cell = [tableView dequeueReusableCellWithIdentifier:upload_pic_cell];
    NSDictionary *dic = self.picArray[indexPath.row];
    cell.sharePicView.yy_imageURL = [NSURL URLWithString:[dic[@"share_pics"] stringByAppendingString:@"?x-oss-process=style/ios_doujin_50"]];
    cell.rewardLabel.text = dic[@"reward"];
    NSArray *statusImages = @[@"icon_examine", @"icon_adopt", @"icon_refuse"];
    NSArray *titleArr = @[@"审核中", @"已通过", @"未通过"];
    NSString *indexStr = (NSString *)dic[@"verify_status"];
    cell.statusImageView.image = [UIImage imageNamed:statusImages[indexStr.integerValue]];
    cell.verifyStatusLabel.text = titleArr[indexStr.integerValue];
    return cell;
}

- (void)postPicData {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/doujin/my-doujins",APP_HOST];
    if (![[NSUserDefaults standardUserDefaults] objectForKey:User_Token]) {
        CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        CZNavigationController *naviVC = rootVC.childViewControllers[0];
        CZMessionCenterViewController *homeVC = (CZMessionCenterViewController *)naviVC.childViewControllers[0];
        CZNavigationController *mineNC = rootVC.childViewControllers[4];
        CZMineViewController *mineVC = mineNC.childViewControllers[0];
        CZUserLoginViewController * loginVC = [[[CZNsjHelper alloc] init] presentLoginViewControllerWithViewCotroller:self];
        @weakify(mineVC);
        loginVC.callBack = ^(){
            [weak_mineVC getUserData];
            [homeVC setUserIconImage];
            weak_mineVC.userIconImageView.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
            [self postPicData];
        };
        return;
    }
    [GCZAFNetWorking POST:urlString params:@{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"content_type" : @"image", @"page" : @(_currentPage)} success:^(id response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSArray *arr = response[@"result"];
            if (!arr || arr.count < 1) {
                [self.uploadPicTableView.mj_footer endRefreshingWithNoMoreData];
                return ;
            }
            if (_currentPage == 1) {
                self.picArray = arr.mutableCopy;
            } else {
                for (NSDictionary *dic in arr) {
                    [self.picArray addObject:dic];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.uploadPicTableView reloadData];
                self.uploadPicTableView.mj_footer.hidden = NO;
            });
            [_refreshView endRefreshing];
            [self.uploadPicTableView.mj_footer endRefreshing];
        } else if ([response[@"code"] isEqualToString:@"300"]) {
            [_refreshView endRefreshing];
            [self.uploadPicTableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [_refreshView endRefreshing];
            [self.uploadPicTableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [_refreshView endRefreshing];
        [self.uploadPicTableView.mj_footer endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
